package com.example.demo1122.config;

import com.example.demo1122.filter.JwtAuthenticationTokenFilter;
import com.example.demo1122.service.impl.AdminUserDetailsService;
import com.example.demo1122.service.impl.CustomAuthenticationFailureHandler;
import com.example.demo1122.service.impl.StudentUserDetailsService;
import com.example.demo1122.service.impl.TeacherUserDetailsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpMethod;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.CorsConfigurationSource;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;

@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    private StudentUserDetailsService studentUserDetailsService;
    @Autowired
    private TeacherUserDetailsService teacherUserDetailsService;
    @Autowired
    private AdminUserDetailsService adminUserDetailsService;
    @Autowired
    private CustomAuthenticationFailureHandler customAuthenticationFailureHandler;
    @Autowired
    JwtAuthenticationTokenFilter jwtAuthenticationTokenFilter;

    @Bean
    public PasswordEncoder passwordEncoder(){
        return new BCryptPasswordEncoder();
    }

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        // 由于您有多个 UserDetailsService，您可能需要一个策略来决定在什么情况下使用哪一个
        auth
                .userDetailsService(studentUserDetailsService).passwordEncoder(passwordEncoder())
                .and()
                .userDetailsService(teacherUserDetailsService).passwordEncoder(passwordEncoder())
                .and()
                .userDetailsService(adminUserDetailsService).passwordEncoder(passwordEncoder());
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
                .cors()
                .and()
                .csrf().disable()
                .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS)
                .and()
                .authorizeRequests()

                .antMatchers(HttpMethod.OPTIONS, "/**").permitAll()
                .antMatchers("/student/login", "/teacher/login","/admin/login").permitAll() // 这里使用permitAll表示允许所有用户访问
                .antMatchers("/**").hasAnyAuthority("ROLE_STUDENT","ROLE_TEACHER","ROLE_ADMIN")
                //.antMatchers("/**").hasAuthority("ROLE_TEACHER")
                //.antMatchers("/**").hasAuthority("ROLE_ADMIN")
                //.antMatchers("/admin/*", "/student/*","/teacher/*","/course/*", "/**").permitAll() // 这里使用permitAll表示允许所有用户访问
                .anyRequest().authenticated()
                .and()
                .formLogin()
                .failureHandler(customAuthenticationFailureHandler)
                .and()
                .httpBasic()
                .and()
                .headers().frameOptions().disable()
                .and()
                .cors().configurationSource(corsConfigurationSource());

        //把token校验过滤器添加到过滤器链中
        http.addFilterBefore(jwtAuthenticationTokenFilter, UsernamePasswordAuthenticationFilter.class);
    }

    @Bean
    public CorsConfigurationSource corsConfigurationSource() {
        CorsConfiguration configuration = new CorsConfiguration();
        configuration.addAllowedOriginPattern("*");
        //configuration.addAllowedOrigin("http://0.0.0.0/"); // 前端域名
        configuration.addAllowedHeader("*");
        configuration.addAllowedMethod("*");
        configuration.setAllowCredentials(true);

        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        source.registerCorsConfiguration("/**", configuration);
        return source;
    }

    @Bean
    @Override
    public AuthenticationManager authenticationManagerBean() throws Exception {
        return super.authenticationManagerBean();
    }
}